package top.zhdev.community.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.zhdev.community.entity.LoginTicket;
import top.zhdev.community.entity.User;
import top.zhdev.community.service.UserService;
import top.zhdev.community.utils.CookieUtil;
import top.zhdev.community.utils.HostHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 登录拦截器，获取登录用户数据
 */
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(LoginTicketInterceptor.class);

    private UserService userService;
    private HostHolder hostHolder;

    @Autowired
    public void setUserService(UserService userService){
        this.userService = userService;
    }

    @Autowired
    public void setHostHolder(HostHolder hostHolder){
        this.hostHolder = hostHolder;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从cooke中获取凭证
        String ticket = CookieUtil.getValue(request,"ticket");
        if(ticket != null){
            // 查询凭证
            LoginTicket loginTicket = userService.getLoginTicket(ticket);
            // 验证凭证是否有效(登录状态是0表示登录，1表是退出状态)
            if(loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())){
                // 根据凭证查询用户
                User user = userService.getUserById(loginTicket.getUserId());
                // 在本次请求中持有用户
                hostHolder.setUser(user);

                // 构建用户认证解惑，并存入SecurityContext，以便于Security进行授权
                // principal:主要信息；credentials:证书；authories：权限
                Authentication authentication = new UsernamePasswordAuthenticationToken(
                        user,user.getPassword(),userService.getAuthorities(user.getId())
                );
                // 存入securityContext
                SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
            }
        }

        return true;
    }

    /**
     * 在模板引擎使用之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if(user != null && modelAndView != null){
            log.info("user信息{}",user.getUsername());
            modelAndView.addObject("loginUser",user);
        }
    }

    /**
     * 完成之后清楚数据
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();;
        // 清除保存权限验证的结果
        SecurityContextHolder.clearContext();
    }
}
